package cn.tedu.tmall.admin.mall.dao.persist.repository.impl;

import cn.tedu.tmall.admin.mall.dao.persist.mapper.CategoryMapper;
import cn.tedu.tmall.admin.mall.dao.persist.repository.ICategoryRepository;
import cn.tedu.tmall.admin.mall.pojo.po.CategoryPO;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.util.List;

@Slf4j
@Repository
public class CategoryRepositoryImpl implements ICategoryRepository {

    @Autowired
    private CategoryMapper categoryMapper;


    @Override
    public Integer countCategoryByName(String name) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("name",name);
        return categoryMapper.selectCount(queryWrapper);
    }

    @Override
    public Integer save(CategoryPO categoryPO) {
        return categoryMapper.insert(categoryPO);
    }

    @Override
    public CategoryPO getCategoryById(Long parentId) {
        return categoryMapper.selectById(parentId);
    }

    @Override
    public Integer countCategoryById(Long parentId) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("id" ,parentId);
        return categoryMapper.selectCount(queryWrapper);
    }

    @Override
    public Boolean existCategory(Long parentId) {
        Integer count = countCategoryById(parentId);
        if (count > 1 ) return true;
        return false;
    }

    @Override
    public Integer updateById(CategoryPO update) {
        return categoryMapper.updateById(update);
    }

    @Override
    public List<CategoryPO> listAll() {
        return categoryMapper.selectList(null);
    }

    @Override
    public List<CategoryPO> getTopCategory() {
        return getCategoryByParentId(0L);
    }

    @Override
    public List<CategoryPO> getChildrenById(Long id) {
        return getCategoryByParentId(id);
    }

    private List<CategoryPO> getCategoryByParentId(Long id) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("parent_id",id);
        return categoryMapper.selectList(queryWrapper);
    }

}
